package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    WebSocketServer webSocketServer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //下单后，需获得购物车该用户的所有菜品数据
        //生成订单信息，设置订单状态和支付状态
        //清空购物车在支付过后
        //1.获取用户的地址信息
        AddressBook addressBook = addressBookMapper.getByAddressId(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.获取该用户的购物车
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getShoppingCartList(shoppingCart);

        if(shoppingCartList == null && shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //生成订单信息
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //设置订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //设置订单状态 -- 1 待付款
        orders.setStatus(1);
        orders.setUserId(BaseContext.getCurrentId());
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付状态 -- 0 未支付
        orders.setPayStatus(0);
        //设置订单相关的地址信息 收货人
        orders.setPhone(addressBook.getPhone());
        String address = addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        orders.setAddress(address);
        orders.setConsignee(addressBook.getConsignee());

        //插入订单表，返回订单 id
        orderMapper.insert(orders);
        //设置订单详情，购物车数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //将购物车的详情信息插入 order_detail表中
        orderDetailMapper.insert(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        //根据订单id获取提交信息
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;

    }

    /**
     * 订单支付处理
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public LocalDateTime payment(OrdersPaymentDTO ordersPaymentDTO) {
        //根据订单号获取
        //支付后修改订单相关信息
        Orders orders = new Orders();
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        //修改支付方式 1 --微信支付
        orders.setPayMethod(1);
        //修改订单状态，支付成功 -- 待商家接单
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        //支付状态 1 --已支付
        orders.setPayStatus(1);
        //添加结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.updateByOrderNumber(orders);

        Orders order = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        LocalDateTime estimatedDeliveryTime = order.getEstimatedDeliveryTime();

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + order.getNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return estimatedDeliveryTime;
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //按条件查询
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> ordersList =  orderMapper.getOrdersPage(ordersPageQueryDTO);
        //查询订单
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders od : ordersList) {
            OrderVO orderVO = new OrderVO();
            //将订单信息封装
            BeanUtils.copyProperties(od,orderVO);
            //查询订单的菜品明细
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(od.getId());
            orderVO.setOrderDetailList(orderDetails);
            orderVOS.add(orderVO);
        }
        return  new PageResult(ordersList.getTotal(),orderVOS);

    }

    @Override
    public OrderVO getOrderById(Long id) {
        Orders order = orderMapper.getByOrderId(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getByOrderId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        if(ordersCancelDTO.getCancelReason()!=null)
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.updateByOrderNumber(orders);
    }



    @Override
    public PageResult pageQueryByAdmin(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //按条件查询
        Page<Orders> ordersList = orderMapper.getOrdersPage(ordersPageQueryDTO);
        //设置订单详情的名字
        String dishName = "";
        //查询订单
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders od : ordersList) {
            OrderVO orderVO = new OrderVO();
            //将订单信息封装
            BeanUtils.copyProperties(od,orderVO);
            //查询订单的菜品明细
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(od.getId());
            for (OrderDetail detail : orderDetails) {
                dishName = dishName  + detail.getName() + " ";
            }
            orderVO.setOrderDetailList(orderDetails);
            orderVO.setOrderDishes(dishName);
            orderVOS.add(orderVO);
        }
        return new PageResult(ordersList.getTotal(),orderVOS);
    }

    @Override
    public OrderStatisticsVO statistic() {

        Integer toBeConfirmed =  orderMapper.getOredrsCountByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.getOredrsCountByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.getOredrsCountByStatus(Orders.DELIVERY_IN_PROGRESS);

        return new OrderStatisticsVO(toBeConfirmed,confirmed,deliveryInProgress);
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderMapper.getByOrderId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateByOrderNumber(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getByOrderId(ordersRejectionDTO.getId());
        //7 -- 退款
        orders.setStatus(7);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.updateByOrderNumber(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.updateByOrderNumber(orders);
    }

    @Override
    public void repetition(Long id) {
       //再来一单。将菜品 copy 到购物车
        List<OrderDetail> details = orderDetailMapper.getByOrdersId(id);

        for (OrderDetail detail : details) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.updateByOrderNumber(orders);

    }

    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
